<template>
  <el-dialog v-model:model-value="showDialog" title="新增礼品包规格" width="780px" @opened="handleOpened" @closed="handleClosed" :close-on-click-modal="false">
    <el-form ref="formRef" :model="form" :label-width="110">
      <!--        商品名称-->
      <goods-name readonly :model-value="form.name">
        <template #append>
          <el-button type="primary" link @click="showEditGoods(form)">查看商品信息</el-button>
        </template>
      </goods-name>

      <!--        商品分类-->
      <goods-type readonly :model-value="form.type"></goods-type>

      <!--        所属商家-->
      <goods-store-name :model-value="form.storeName"></goods-store-name>

      <!--        商品规格-->
      <product-selector
          v-model:model-value="selectedProductId"
          :gift-pack-page-row="rowData"
          :options="currentStoreProducts"
          @change="handleGoodsProductChange">
        <template #append>
          <el-button
              type="primary"
              link
              @click="showEditProduct(currentGoodsEntity, currentProduct)">
            查看规格信息
          </el-button>
        </template>
      </product-selector>

      <!--        商家规格预占剩余库存-->
      <product-before-stock :value="currentProduct.beforeStock"></product-before-stock>

      <product-stock-add-or-decount
          v-if="rowData.packNum !== -1"
          v-model:model-value="form.addOrDeductionStockCount">
      </product-stock-add-or-decount>

      <el-form-item prop="prize" :rules="prizeRules"></el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="showDialog=false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>

  <!--    编辑商品 (查看商品信息)-->
  <edit-goods
      v-model:show="isShowEditGoods"
      :row-data="currentEditingRow"
      @click-submit="handleEditGoodsDone"
  ></edit-goods>

  <!--  编辑规格-->
  <edit-gift-pack-product
      v-model:show="isShowEditProduct"
      :form-props="['name', 'thumbnailUrl']"
      :gift-pack-form="form"
      :product-row-data="currentProductRowForEditProduct"
      :row-data="currentGoodsRowForEditProduct"
      @click-submit="handleEditProductDone">
  </edit-gift-pack-product>
</template>

<script lang="ts" setup>
import {Ref, WritableComputedRef} from "vue";
import {IGoodsPageRow, IStoreGoodsPageRow} from "@/api/modules/pointsMall";

// 奖品
import GoodsName from "@/components/goodsCenter/addGoodsFormItem/GoodsName.vue"
import GoodsType from "@/components/goodsCenter/addGoodsFormItem/GoodsType.vue"
import GoodsStoreName from "@/components/goodsCenter/addGoodsFormItem/GoodsStoreName.vue"
import ProductSelector from "@/components/goodsCenter/addGoodsFormItem/ProductSelector.vue"
import ProductBeforeStock from "@/components/goodsCenter/addProductFormItem/ProductBeforeStock.vue"
import ProductStockAddOrDecount from "@/components/goodsCenter/addGiftPackFormItem/ProductStockAddOrDecount.vue";
import {useAddGiftPackPrize} from "@/components/goodsCenter/compositions/useAddGiftPackPrize";
import {IGiftPackGoodProduct, IGiftPackGoodsEntity} from "@/api/modules/vipCenter";
import {useEditGoods} from "@/components/goodsCenter/compositions/useEditGoods";
import {useEditProduct} from "@/components/goodsCenter/compositions/useEditProduct";

const props = defineProps<{
  show: boolean,
  rowData: IGoodsPageRow,
  storeRowData: IStoreGoodsPageRow,
}>()

const emits = defineEmits<{
  (e: 'update:show', val: boolean):void,
  (e: 'confirm', val: IGiftPackGoodsEntity): void
}>()

const {makeGoodsEntity, makeGoodsProduct} = useAddGiftPackPrize()

const showDialog:WritableComputedRef<boolean> = computed({
  get() {
    return props.show
  },
  set(val) {
    return emits("update:show", val)
  }
})

const form:Ref<IGiftPackGoodsEntity> = ref({} as any)

const currentStoreProducts = computed(() => {
  return props.storeRowData?.products ?? []
})
const selectedProductId:Ref<number | null> = ref(null)

const currentProduct = computed(() => {
  return form.value?.products?.[0] ?? {}
})

// 数量校验
const prizeRules = [{
  validator(rule: any, value: any, callback: any) {
    // 新增规格一定会满足 规格数量比礼品包数量大 因此不需要新增礼品包里的此相同规则
    callback()
  }
}]

const handleGoodsProductChange = (storeProductId: number) => {
  const targetProduct = currentStoreProducts.value.find(item => item.id === storeProductId)
  if (!targetProduct) {
    return
  }

  // 单一规格
  if (form.value.products) {
    form.value.products[0] = makeGoodsProduct(targetProduct, props.storeRowData)
  }
}

// 编辑商品
const {isShowEditGoods, showEditGoods, currentEditingRow} = useEditGoods()
const handleEditGoodsDone = (editForm:any) => {
  isShowEditGoods.value = false

  form.value = {...editForm}
}

// 编辑规格
const {
  isShowEditProduct,
  showEditProduct,
  currentGoodsRowForEditProduct,
  currentProductRowForEditProduct
} = useEditProduct()
const handleEditProductDone = (editForm:IGiftPackGoodProduct) => {
  isShowEditProduct.value = false
  form.value.products = [{...editForm}]
}

const handleConfirm = () => {
  // console.log('form', form)
  if (props.rowData.packNum !== -1) {
    form.value.products.forEach(item => item.addOrDeductionStockCount = form.value.addOrDeductionStockCount)
  }

  emits('confirm', form.value)
}

const handleOpened = () => {
  const _form = makeGoodsEntity(props.storeRowData)
  _form.parentId = props.rowData.id

  // 默认选中第一个product
  // form --> product
  if (props.storeRowData.products?.[0]) {
    const storeProduct = props.storeRowData.products[0]
    _form.products!.push(makeGoodsProduct(storeProduct, props.storeRowData))
    selectedProductId.value = storeProduct.id
  }

  form.value = _form
}

const handleClosed = () => {
  form.value = makeGoodsEntity(props.storeRowData)
}
</script>

<style scoped lang="scss">

</style>
